<!-- 创建模型 -->
<template>
  <div>
    <div class="header">
      <a-icon-font class="icon" type="iconqiehuantufenxibeifen2" />
      <span>模型训练</span>
      <div class="divider"></div>
      <div class="tab">
        <span class="m-span">我的模型</span>
        <div class="bottom-line"></div>
      </div>
    </div>
    <div class="model-report">
      <div class="bg">
        <div class="navg-btns">
          <div class="return-btn" @click="backList">
            <a-icon type="left" />返回
          </div>
          <div class="divider2"></div>
          <a-breadcrumb class="bread">
            <span slot="separator">|</span>
            <a-breadcrumb-item><a>模型评估</a></a-breadcrumb-item>
          </a-breadcrumb>
          <a-button
            class="export-btn"
            type="primary"
            @click="exportVisible = true"
            >导出模型</a-button
          >
        </div>
        <a-divider style="margin: 0;"></a-divider>
        <a-spin :spinning="loading" size="large" tip="Loading...">
          <div style="height: 100%;">
            <div class="content1">
              <!--模型训练 训练完成/未训练-->
              <div class="title">
                <b>{{
                  `${modelData.name} [${modelData && modelData.modelType}-${
                    modelData && modelData.algorithm
                  }]`
                }}</b>
              </div>
              <a-row class="row">
                <a-col :span="8"
                  >数据规模：{{
                    modelData.data ? `${modelData.data.rowNum}行` : '-'
                  }}</a-col
                >
                <a-col :span="8"
                  >字段数：{{
                    modelData.data ? modelData.data.colNum : '-'
                  }}</a-col
                >
                <a-col :span="8"
                  >训练时长：{{
                    modelData.runTime ? `${modelData.runTime}s` : '-'
                  }}</a-col
                >
              </a-row>
              <a-row class="row">
                <a-col :span="8"
                  >创建时间：{{
                    modelData.gmtCreate ? modelData.gmtCreate : '-'
                  }}</a-col
                >
                <a-col :span="8"
                  >大小：{{
                    modelData.data && modelData.data.sourceSize
                      ? modelData.data.sourceSize
                      : '-'
                  }}</a-col
                >
              </a-row>
            </div>
            <div class="diviver"></div>
            <div class="content2">
              <a-radio-group v-model="radio" class="radio" button-style="solid">
                <a-radio-button value="a">评估报告</a-radio-button>
                <a-radio-button value="b" @click="queryOutputById"
                  >输出结果</a-radio-button
                >
              </a-radio-group>

              <div class="content" style="height: 100%; width: 100%;">
                <model-access
                  v-if="radio === 'a' && !loading"
                  :project-id="projectId"
                  :model-id="modelId"
                  :model-data="modelData"
                  :algorithm="modelData.algorithm"
                  :is-report="true"
                  @train-status="queryModelById(modelId)"
                ></model-access>
                <div v-else>
                  <div class="m_title">
                    <div class="divider"></div>
                    <strong>输出结果</strong>
                    <div class="download-btn">
                      <a-dropdown :trigger="['click']">
                        <div>
                          <a-icon-font
                            class="icon"
                            type="iconxiazaibendi"
                          ></a-icon-font
                          >下载
                        </div>
                        <a-menu slot="overlay">
                          <a-menu-item key="0" @click="openSave"
                            >到数据集</a-menu-item
                          >
                          <a-menu-item key="1" @click="saveToLocal"
                            >到本地</a-menu-item
                          >
                        </a-menu>
                      </a-dropdown>
                    </div>
                  </div>
                  <a-table
                    :loading="tableLoading"
                    :columns="columns"
                    :data-source="souceData"
                  ></a-table>
                  <!-- <a-pagination v-model="curPage" :total="totalPages*10" align="right" style="margin-top: 16px;" show-less-items /> -->
                </div>
              </div>
            </div>
          </div>
        </a-spin>

        <div class="close" @click="closeGraphPanel">
          <a-icon title="关闭" type="close" />
        </div>
      </div>

      <!-- 导出框 -->
      <a-modal
        :visible="exportVisible"
        :ok-text="'保存'"
        cancel-text="取消"
        centered
        :width="458"
        title="导出模型"
        @cancel.stop="
          exportVisible = false
          modelForm = {}
        "
        @ok="handleConfirm"
      >
        <div>
          <a-form
            :form="modelForm"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-form-item label="导出至：">
              <a-input
                v-if="collectionList.length < 1"
                disabled
                placeholder="我的模型"
              ></a-input>
              <a-select
                v-else
                ref="select"
                v-model="modelForm.id"
                class="model-radius"
                placeholder="请选择"
                allow-clear
              >
                <a-select-option
                  v-for="(item, index) in collectionList"
                  :key="index"
                  :value="item.id"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="模型名称：">
              <a-input
                ref="classInput"
                v-model="modelData.name"
                default-value="未命名"
                :allow-clear="true"
                class="model-radius"
              >
              </a-input>
              <!-- <a-input
                ref="classInput"
                v-model="modelForm.name"
                default-value="未命名"
                :allow-clear="true"
                class="model-radius"
              >
              </a-input> -->
            </a-form-item>
            <a-form-item label="功能描述：">
              <a-textarea
                v-model="modelForm.modelDesc"
                placeholder="创建时的功能性描述"
                :rows="6"
              />
            </a-form-item>
          </a-form>
        </div>
      </a-modal>

      <!-- 保存至数据管理 保存至数据集-->
      <a-modal
        title="保存至数据集"
        :visible="saveVisible"
        ok-text="确定"
        cancel-text="取消"
        centered
        :width="578"
        destroy-on-close
        @ok="saveData"
        @cancel.stop="cancelSave"
      >
        <div class="saveData-modal">
          <a-form
            :form="dataMgtForm"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-form-item label="选择数据分类：">
              <a-select
                ref="select"
                v-model="dataMgtForm.categoryId"
                class="model-radius"
                placeholder="请选择"
                :disabled="newClassVisible"
                allow-clear
              >
                <a-select-option
                  v-for="(item, index) in userDataList"
                  :key="index"
                  :value="item.categoryId"
                >
                  {{ item.categoryName }}
                </a-select-option>
              </a-select>
              <span
                class="m-span"
                :class="{ disabled: newClassVisible }"
                @click="addClass"
                ><a-icon-font class="icon" type="iconzengjia"></a-icon-font
                >新建分类</span
              >
            </a-form-item>
            <a-form-item v-if="newClassVisible" label="数据分类名：">
              <a-input
                ref="classInput"
                v-model="dataMgtForm.categoryName"
                placeholder="未命名"
                allow-clear
                class="model-radius"
              >
              </a-input>
              <span class="delete" @click="newClassVisible = false"
                ><a-icon-font type="iconicon-beifen5"></a-icon-font
              ></span>
            </a-form-item>
            <a-form-item label="数据名：">
              <a-input
                v-model="dataMgtForm.datasetName"
                placeholder="请填写"
                :allow-clear="true"
                class="model-radius"
              >
              </a-input>
            </a-form-item>
          </a-form>
        </div>
      </a-modal>
    </div>
    <!-- <div class="ant-modal-mask" style="z-index: 998;"></div> -->
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import ModelAccess from '@/components/studio/data/model/ModelAccess.vue'
import DatasetPreviewTable from '@/components/data/DatasetPreviewTable.vue'
import {
  queryModelById,
  exportToFolder,
  queryOutputById,
  saveOutputToDataSource,
} from '@/api/model'
import { allOperatorList } from '@/api/operator-list'
import DataViewStore from '@/store/modules/dataview'
import { queryUserDatalist, checkDatasetName } from '@/api/data-list'
import { baseURL } from '@/api/axios-config'

@Component({
  components: { ModelAccess, DatasetPreviewTable },
})
export default class ModelTrainning extends Vue {
  // @Prop({ type: Number, default: 0 }) projectId!: number
  private projectId: number = 0 // 项目 Id
  public modelData: any = {}
  public modelId: number = 0
  public loading: boolean = false
  public tableLoading: boolean = false
  public dataFm: any = {}
  public modelForm: any = {}
  public radio: any = 'a'
  public columns: any = []
  public souceData: any = []
  public exportVisible: boolean = false
  public collectionList: any = []
  public curPage: number = 1
  public totalPages: number = 0
  // 保存至数据集 弹窗显示
  public saveVisible: boolean = false
  // 保存至数据集 form
  public dataMgtForm: any = {}
  // 新建分类是否显示
  public newClassVisible: boolean = false
  // 用户数据列表(加载)
  public userDataList: Array<any> = []

  @Watch('curPage')
  public curPageChange() {
    this.queryOutputById()
  }

  public async queryOperatorList() {
    const response = await allOperatorList({
      data: { projectId: this.projectId },
    })
    if (response.data.code === 100) {
      this.collectionList = []
      this.collectionList.push({
        id: '我的模型',
        name: response.data.result.panel.slice(-1)[0].name,
      })
      response.data.result.panel.slice(-1)[0].items.forEach((element: any) => {
        if (element.isFolder) {
          this.collectionList.push({ id: element.id, name: element.name })
        }
      })
      DataViewStore.setOperatorList(response.data.result.panel)
    }
  }

  public async queryOutputById() {
    this.tableLoading = true
    const response = await queryOutputById({
      data: {
        projectId: this.projectId,
        id: this.modelId,
        // start: (this.curPage-1)*10+1,
        // end: this.curPage*10
      },
    })
    this.tableLoading = false
    if (response.data.code === 100) {
      // console.log(response.data.result)
      this.columns = []
      response.data?.result?.head.forEach((element: any) => {
        this.columns.push({
          title: element.name,
          key: element.name,
          dataIndex: element.name,
          // slots: { title: 'customTitle' },
        })
      })
      this.totalPages = response.data.result.totalPages
      // console.log(this.totalPages)
      this.souceData = response.data.result.data
    } else {
      this.$message.error(response.data.message)
    }
  }

  // 加载数据  获取用户所有数据
  public LoadData() {
    queryUserDatalist({ data: { projectId: this.projectId } })?.then(
      (response: any) => {
        if (response.data.code === 100) {
          this.userDataList = response.data.result
        }
      }
    )
  }

  // 弹窗-新建分类
  public addClass() {
    this.$nextTick(() => {
      if (this.dataMgtForm.categoryId) {
        this.dataMgtForm.categoryId = undefined
      }
      if (this.dataMgtForm.categoryName) {
        this.dataMgtForm.categoryName = undefined
      }

      const name = this.$refs.classInput as HTMLElement // 使用ref需要用v-show代替v-if
      // @ts-ignore
      setTimeout(function () {
        name?.focus()
      }, 300) // 延迟focus，否则不生效
    })
    this.newClassVisible = true
  }

  // 保存数据
  public openSave() {
    this.LoadData()
    this.dataMgtForm = {}
    this.saveVisible = true
  }

  public saveToLocal() {
    // 保存至本地 projectId=${this.projectId}&
    window.open(`${baseURL}/model/downloadOutput?modelId=${this.modelData.id}`)
  }

  // 取消保存
  public cancelSave() {
    this.newClassVisible = false
    this.saveVisible = false
    this.dataMgtForm = {}
  }

  /**
   * 保存数据
   */
  public async saveData() {
    if (!this.newClassVisible) {
      if (!this.dataMgtForm.categoryId) {
        this.$message.error('请选择数据分类！')
        return
      }
      if (!this.dataMgtForm.datasetName) {
        this.$message.error('请填写数据名！')
        return
      }
      // 非新建数据分类 需要检测同名数据集
      const response = await this.checkDatasetName()
      if (response.data.code === 100) {
        if (response.data.result) {
          this.$message.error(response.data.tips, 3)
        } else {
          this.saveDataApi()
        }
      }
    } else {
      if (!this.dataMgtForm.categoryName) {
        this.$message.error('请填写数据分类名！')
        return
      }
      if (!this.dataMgtForm.datasetName) {
        this.$message.error('请填写数据名！')
        return
      }
      this.saveDataApi()
    }
  }

  // 检测同名数据集
  public async checkDatasetName() {
    const response = await checkDatasetName({
      data: {
        categoryId: this.dataMgtForm.categoryId,
        datasetName: this.dataMgtForm.datasetName,
      },
    })
    return response
  }

  public saveDataApi() {
    const parameters = {
      categoryId: this.dataMgtForm.categoryId,
      datasetName: this.dataMgtForm.datasetName,
      categoryName: this.dataMgtForm.categoryName,
      projectId: this.projectId,
      modelId: this.modelData.id,
    }
    saveOutputToDataSource({ data: parameters })?.then((response1: any) => {
      if (response1.data.code === 100) {
        this.$message.success('保存成功！')
        DataViewStore.loadProjectData(this.projectId)
        this.saveVisible = false
      } else {
        this.$message.error(response1.data.message)
      }
    })
  }

  public created() {
    this.projectId = Number(this.$route.params.id)
    this.modelId = Number(this.$route.query.id)
    this.radio = this.$route.query.type
    this.queryModelById(this.modelId)
    if (this.radio === 'b') {
      this.queryOutputById()
    }
    this.queryOperatorList()
  }

  public async queryModelById(modelId: any) {
    this.loading = true
    await queryModelById({
      // data: { projectId: this.projectId,id:this.pipelineId },
      data: { projectId: this.projectId, id: modelId, data: {} },
    })
      .then(async (response: any) => {
        this.loading = false
        if (response.data.code === 100) {
          this.modelData = response.data.result
          this.dataFm.source = this.modelData.sourceTable
          switch (this.modelData.algorithm) {
            case 'LR': {
              if (this.modelData.param?.label_col) {
                this.dataFm.label_col = this.modelData.param?.label_col
              }
              // this.dataFm.label_col = this.modelData?.param?.label_col ?? undefined
              // console.log(this.dataFm.label_col)
              this.dataFm.max_iter = this.modelData.param?.max_iter ?? 20
              this.dataFm.reg_param = this.modelData.param?.reg_param ?? 0
              break
            }
            case 'DTC': {
              this.dataFm.max_depth = this.modelData.param?.max_depth ?? 5
              // this.dataFm.label_col = this.modelData?.param?.label_col ?? ''
              if (this.modelData.param?.label_col) {
                this.dataFm.label_col = this.modelData.param?.label_col
              }
              this.dataFm.split_rate = [undefined, undefined]
              break
            }
            case 'KM': {
              this.dataFm.k = this.modelData.param?.k ?? 2
              this.dataFm.max_iter = this.modelData.param?.max_iter ?? 20
              this.dataFm.model_type =
                this.modelData.param?.model_type ?? 'euclidean'
              break
            }
            case 'PCA': {
              this.dataFm.k = this.modelData.param?.k ?? 1
              break
            }
            default:
              break
          }
        }
      })
      .catch(() => {
        this.loading = false
      })
  }

  public async handleConfirm() {
    if (!this.modelForm.id) {
      this.$message.error('请选择文件夹！')
      return
    }
    let FOLDER_ID = this.modelForm.id
    if (this.modelForm.id === '我的模型') {
      FOLDER_ID = ''
    }
    const response = await exportToFolder({
      data: {
        projectId: this.projectId,
        id: this.modelId,
        folderId: FOLDER_ID,
        name: this.modelForm.name,
        modelDesc: this.modelForm.modelDesc,
      },
    })
    this.exportVisible = false
    this.modelForm = {}
    if (response.data.code === 100) {
      this.$message.success('导出成功！')
    }
  }

  public filterModelType(type: any) {
    switch (type) {
      case 'LR':
        return '线性回归'
      case 'DTC':
        return '决策树'
      case 'KM':
        return 'K均值'
      case 'PCA':
        return '主成分分析'
      case 'AUTOC':
        return '分类自动机器学习'
      case 'AUTOR':
        return '回归自动机器学习'
      default:
        return ''
    }
  }

  public backList() {
    this.$router.push(this.$route.path.replace(/report/, 'trainning'))
  }

  public closeGraphPanel() {
    this.$router.push({ name: '数据视图' })
  }
}
</script>

<style lang="less" scoped>
@import '@/styles/model';

// .body {
//   background-color: #fafafa;
//   height: 100%;
//   overflow-x: hidden;
//   padding: 16px 24px;
//   position: relative;
//   width: 100%;
//   z-index: 999;

//   .bg {
//     background: #fff;
//     height: 100%;

//     .navg-btns {
//       align-items: center;
//       display: flex;

//       .export-btn {
//         position: absolute;
//         right: 60px;
//       }

//       .bread {
//         background-color: #fff;
//         margin-bottom: 1px;
//         padding: 16px 0 16px 2px;
//       }

//       .return-btn {
//         align-items: center;
//         color: #6973ff;
//         cursor: pointer;
//         display: flex;
//         padding: 16px 8px 16px 24px;

//         .icon {
//           margin-right: 4px;
//         }
//       }
//     }

//     .content1 {
//       padding: 24px;

//       .title {
//         font-size: 16px;
//         margin-bottom: 20px;
//       }

//       .row {
//         padding: 4px 0;
//       }
//     }

//     .content2 {
//       padding: 24px;

//       .radio {
//         margin-bottom: 24px;
//       }
//     }
//   }
// }

// .diviver {
//   background: #fafafa;
//   height: 16px;
//   width: 100%;
// }

// .m_checkbox {
//   background-color: #fafafa;
//   border-radius: 4px;
//   padding-left: 12px;
//   width: 100%;
// }

// .m_radiobox {
//   background-color: #fafafa;
//   border-radius: 4px;
//   padding: 8px;
//   width: 100%;
// }

// .m_title {
//   align-items: center;
//   display: flex;
//   margin-bottom: 22px;

//   b {
//     font-size: 16px;
//   }
// }

// .divider {
//   background-color: #6973ff;
//   height: 18px;
//   margin-right: 8px;
//   width: 4px;
// }

// .divider2 {
//   background-color: rgba(93, 99, 126, 0.45);
//   height: 18px;
//   margin-right: 8px;
//   width: 1px;
// }

// .close {
//   color: #fff;
//   cursor: pointer;
//   font-size: 20px;
//   line-height: 64px;
//   position: fixed;
//   right: 20px;
//   top: -2px;
// }

// /deep/.ant-table td { white-space: nowrap; }
</style>
